package com.muyu.marketing.bargain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.marketing.bargain.domain.BargainProduct;
import com.muyu.marketing.bargain.domain.BargainRecord;
import com.muyu.marketing.bargain.domain.req.BargainRecordReq;
import com.muyu.marketing.bargain.mapper.BargainProductMapper;
import com.muyu.marketing.bargain.mapper.BargainRecordMapper;
import com.muyu.marketing.bargain.service.BargainRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 砍价记录Service业务层处理
 * 
 * @author muyu
 * @date 2025-01-27
 */
@Service
public class BargainRecordServiceImpl extends ServiceImpl<BargainRecordMapper, BargainRecord> implements BargainRecordService {
    
    @Autowired
    private BargainRecordMapper bargainRecordMapper;
    
    @Autowired
    private BargainProductMapper bargainProductMapper;
    
    @Override
    public List<BargainRecord> selectBargainRecordList(BargainRecord bargainRecord) {
        return bargainRecordMapper.selectBargainRecordList(bargainRecord);
    }
    
    @Override
    public BargainRecord selectBargainRecordById(Long id) {
        return bargainRecordMapper.selectById(id);
    }
    
    @Override
    public BargainRecord selectBargainRecordByUserAndProduct(Long userId, Long bargainProductId) {
        return bargainRecordMapper.selectBargainRecordByUserAndProduct(userId, bargainProductId);
    }
    
    @Override
    public List<BargainRecord> selectBargainRecordListByProductId(Long bargainProductId) {
        return bargainRecordMapper.selectBargainRecordListByProductId(bargainProductId);
    }
    
    @Override
    public List<BargainRecord> selectBargainRecordListByUserId(Long userId) {
        return bargainRecordMapper.selectBargainRecordListByUserId(userId);
    }
    
    @Override
    public int insertBargainRecord(BargainRecordReq bargainRecordReq) {
        BargainRecord bargainRecord = new BargainRecord();
        BeanUtils.copyProperties(bargainRecordReq, bargainRecord);
        bargainRecord.setCreateTime(DateUtils.getNowDate());
        return bargainRecordMapper.insert(bargainRecord);
    }
    
    @Override
    public int updateBargainRecord(BargainRecord bargainRecord) {
        return bargainRecordMapper.updateById(bargainRecord);
    }
    
    @Override
    public int deleteBargainRecordByIds(Long[] ids) {
        for (Long id : ids) {
            deleteBargainRecordById(id);
        }
        return ids.length;
    }
    
    @Override
    public int deleteBargainRecordById(Long id) {
        return bargainRecordMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public BargainRecord startBargain(Long userId, Long bargainProductId) {
        // 检查砍价商品是否存在且可砍价
        BargainProduct bargainProduct = bargainProductMapper.selectById(bargainProductId);
        if (bargainProduct == null) {
            throw new RuntimeException("砍价商品不存在");
        }
        
        if (bargainProduct.getBargainStatus() != 1) {
            throw new RuntimeException("砍价商品未开始或已结束");
        }
        
        if (bargainProduct.getStock() <= 0) {
            throw new RuntimeException("砍价商品库存不足");
        }
        
        // 检查用户是否已有砍价记录
        BargainRecord existingRecord = selectBargainRecordByUserAndProduct(userId, bargainProductId);
        if (existingRecord != null) {
            if (existingRecord.getRecordStatus() == 0) {
                // 进行中，返回现有记录
                return existingRecord;
            } else if (existingRecord.getRecordStatus() == 1) {
                // 已完成，不能重复砍价
                throw new RuntimeException("您已完成该商品的砍价");
            }
        }
        
        // 创建新的砍价记录
        BargainRecord bargainRecord = new BargainRecord();
        bargainRecord.setBargainProductId(bargainProductId);
        bargainRecord.setUserId(userId);
        bargainRecord.setBargainAmount(BigDecimal.ZERO);
        bargainRecord.setCurrentPrice(bargainProduct.getBargainPrice());
        bargainRecord.setRecordStatus(0); // 进行中
        bargainRecord.setBargainCount(0);
        bargainRecord.setRemainingCount(bargainProduct.getBargainLimit());
        bargainRecord.setIsMinPrice(0);
        bargainRecord.setStartTime(DateUtils.getNowDate());
        bargainRecord.setEndTime(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)); // 24小时后结束
        bargainRecord.setCreateTime(DateUtils.getNowDate());
        
        bargainRecordMapper.insert(bargainRecord);
        
        // 更新砍价商品砍价人数
        bargainProductMapper.updateBargainers(bargainProductId, 1);
        
        return bargainRecord;
    }
    
    @Override
    @Transactional
    public BargainRecord executeBargain(Long userId, Long bargainProductId) {
        // 获取砍价记录
        BargainRecord bargainRecord = selectBargainRecordByUserAndProduct(userId, bargainProductId);
        if (bargainRecord == null) {
            throw new RuntimeException("砍价记录不存在，请先开始砍价");
        }
        
        if (bargainRecord.getRecordStatus() != 0) {
            throw new RuntimeException("砍价已结束");
        }
        
        if (bargainRecord.getRemainingCount() <= 0) {
            throw new RuntimeException("砍价次数已用完");
        }
        
        // 获取砍价商品信息
        BargainProduct bargainProduct = bargainProductMapper.selectById(bargainProductId);
        if (bargainProduct == null) {
            throw new RuntimeException("砍价商品不存在");
        }
        
        // 计算砍价金额
        BigDecimal bargainAmount = calculateBargainAmount(bargainProduct, bargainRecord);
        
        // 更新砍价记录
        BigDecimal newCurrentPrice = bargainRecord.getCurrentPrice().subtract(bargainAmount);
        if (newCurrentPrice.compareTo(bargainProduct.getMinBargainPrice()) < 0) {
            newCurrentPrice = bargainProduct.getMinBargainPrice();
            bargainAmount = bargainRecord.getCurrentPrice().subtract(newCurrentPrice);
        }
        
        int newBargainCount = bargainRecord.getBargainCount() + 1;
        int newRemainingCount = bargainRecord.getRemainingCount() - 1;
        
        // 检查是否达到最低价格
        int isMinPrice = newCurrentPrice.compareTo(bargainProduct.getMinBargainPrice()) <= 0 ? 1 : 0;
        
        bargainRecordMapper.updateBargainInfo(
            bargainRecord.getId(),
            bargainAmount,
            newCurrentPrice,
            newBargainCount,
            newRemainingCount
        );
        
        // 更新记录对象
        bargainRecord.setBargainAmount(bargainRecord.getBargainAmount().add(bargainAmount));
        bargainRecord.setCurrentPrice(newCurrentPrice);
        bargainRecord.setBargainCount(newBargainCount);
        bargainRecord.setRemainingCount(newRemainingCount);
        bargainRecord.setIsMinPrice(isMinPrice);
        
        // 如果达到最低价格或砍价次数用完，完成砍价
        if (isMinPrice == 1 || newRemainingCount <= 0) {
            completeBargain(bargainRecord.getId());
            bargainRecord.setRecordStatus(1);
        }
        
        return bargainRecord;
    }
    
    @Override
    @Transactional
    public int completeBargain(Long id) {
        BargainRecord bargainRecord = selectBargainRecordById(id);
        if (bargainRecord == null) {
            throw new RuntimeException("砍价记录不存在");
        }
        
        // 更新砍价记录状态
        bargainRecord.setRecordStatus(1);
        bargainRecord.setCompleteTime(DateUtils.getNowDate());
        bargainRecord.setUpdateTime(DateUtils.getNowDate());
        
        int result = bargainRecordMapper.updateById(bargainRecord);
        
        // 更新砍价商品成功砍价数
        bargainProductMapper.updateSuccessfulBargains(bargainRecord.getBargainProductId(), 1);
        
        // 更新砍价商品销量
        bargainProductMapper.updateSales(bargainRecord.getBargainProductId(), 1);
        
        // 更新砍价商品库存
        bargainProductMapper.updateStock(bargainRecord.getBargainProductId(), -1);
        
        return result;
    }
    
    @Override
    public int cancelBargain(Long id) {
        BargainRecord bargainRecord = new BargainRecord();
        bargainRecord.setId(id);
        bargainRecord.setRecordStatus(2); // 已取消
        bargainRecord.setUpdateTime(DateUtils.getNowDate());
        return bargainRecordMapper.updateById(bargainRecord);
    }
    
    @Override
    public Integer countBargainersByProductId(Long bargainProductId) {
        return bargainRecordMapper.countBargainersByProductId(bargainProductId);
    }
    
    @Override
    public Integer countSuccessfulBargainsByProductId(Long bargainProductId) {
        return bargainRecordMapper.countSuccessfulBargainsByProductId(bargainProductId);
    }
    
    /**
     * 计算砍价金额
     */
    private BigDecimal calculateBargainAmount(BargainProduct bargainProduct, BargainRecord bargainRecord) {
        // 基于当前价格和最低砍价价格计算砍价金额
        BigDecimal currentPrice = bargainRecord.getCurrentPrice();
        BigDecimal minBargainPrice = bargainProduct.getMinBargainPrice();
        
        // 计算可砍价的最大金额（当前价格 - 最低砍价价格）
        BigDecimal maxBargainAmount = currentPrice.subtract(minBargainPrice);
        
        // 如果已经达到最低价格，返回0
        if (maxBargainAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        
        // 使用砍价价格作为基础砍价金额
        BigDecimal baseBargainAmount = bargainProduct.getBargainPrice();
        
        // 确保砍价金额不超过最大可砍价金额
        if (baseBargainAmount.compareTo(maxBargainAmount) > 0) {
            baseBargainAmount = maxBargainAmount;
        }
        
        // 添加随机因素，让砍价金额在基础金额的50%-100%之间
        Random random = new Random();
        double randomFactor = 0.5 + random.nextDouble() * 0.5; // 0.5-1.0之间
        BigDecimal randomAmount = baseBargainAmount.multiply(BigDecimal.valueOf(randomFactor));
        
        return randomAmount.setScale(2, RoundingMode.HALF_UP);
    }
}